package dfs_bfs.test93;

import java.util.ArrayList;
import java.util.List;

/**
 * @author code_yc
 * @version 1.0
 * @date 2020/7/8 15:28
 */
public class Solution1 {

    List<String> ans = new ArrayList<>();

    public List<String> restoreIpAddresses(String s) {
        if (s.length() < 4 || s.length() > 12) return ans;
        dfs(s, 0, 0, new StringBuilder());
        return ans;
    }

    private void dfs(String s, int c, int k, StringBuilder path) {
        if (c == s.length()) {
            if (k == 4) {
                ans.add(new String(path.substring(0, path.length() - 1)));
                return;
            }
            return;
        }
        if (k > 4) return;
        StringBuilder before = new StringBuilder(path);
        if (s.charAt(c) == '0') {
            dfs(s, c + 1, k + 1, path.append("0."));
        } else {
            int pre = 0;
            for (int i = 0; i < 3 && i + c < s.length(); i++) {
                pre = pre * 10 + (s.charAt(i + c) - '0');
                if (pre < 256) {
                    path = new StringBuilder(before);
                    path.append(s.substring(c, c + i + 1) + ".");
                    dfs(s, i + c + 1, k + 1, path);
                }
            }
        }
    }
}
